package com.yuanchu.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.utils.PageResult;
import com.yuanchu.store.dao.YoshopHelpDao;
import com.yuanchu.store.dto.EditHelpParamsDto;
import com.yuanchu.store.dto.QueryPageParams;
import com.yuanchu.store.entity.YoshopHelpEntity;
import com.yuanchu.store.service.YoshopHelpService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.yuanchu.common.utils.DateFormatUtils.formatDatetime;


@Service("yoshopHelpService")
public class YoshopHelpServiceImpl extends ServiceImpl<YoshopHelpDao, YoshopHelpEntity> implements YoshopHelpService {


    @Override
    public PageResult<YoshopHelpEntity> queryHelpList(QueryPageParams params) {
        if (params == null){
            params = new QueryPageParams();
        }
        Integer page = params.getPage();
        Integer pagesize = params.getPagesize();
        QueryWrapper<YoshopHelpEntity> queryWrapper = new QueryWrapper<YoshopHelpEntity>().eq("is_delete", 0);
        Page<YoshopHelpEntity> page1 = new Page<>(page, pagesize);
        Page<YoshopHelpEntity> page2 = this.page(page1, queryWrapper);
        List<YoshopHelpEntity> records = page2.getRecords();
        records.forEach(item -> {
            item.setCreateTime(formatDatetime(item.getCreateTime()));
            item.setUpdateTime(formatDatetime(item.getUpdateTime()));
        });
        PageResult<YoshopHelpEntity> result = new PageResult<>();
        result.setTotal(Math.toIntExact(records.size()));
        result.setCurrentPage(page);
        result.setData(records);
        result.setPerPage(15);
        long total = records.size();
        // 计算总页数，向下取整避免超出实际页数（这里已假设pageInfo.getTotal()返回的是long类型）
        int totalPages = (int) Math.ceil((double) total / 15);
        result.setLastPage(totalPages);
        return result;
    }

    @Override
    public void editHelp(EditHelpParamsDto params) {
        YoshopHelpEntity yoshopHelp = params.getForm();
        yoshopHelp.setHelpId(params.getHelpId());
        yoshopHelp.setUpdateTime(String.valueOf(System.currentTimeMillis()/1000));
        this.updateById(yoshopHelp);
    }

    @Override
    public void deleteHelp(EditHelpParamsDto params) {
        Integer helpId = params.getHelpId();
        this.removeById(helpId);
    }

    @Override
    public void addHelp(YoshopHelpEntity form) {
        YoshopHelpEntity help = new YoshopHelpEntity();
        BeanUtils.copyProperties(form, help);
        help.setCreateTime(String.valueOf(System.currentTimeMillis()/1000));
        help.setUpdateTime(String.valueOf(System.currentTimeMillis()/1000));
        help.setStoreId(10001);
        this.save(help);
    }

}